//  存放路由处理函数模块, 为了保证路由模块的纯粹性
const { 
    checkPassword,
    checkUsername 
} = require('../utils/common')

const path = require('path')
const sqlPath = path.join(__dirname, 'sql/index')
const { isRegisterSql, addRegisterSql, checkLoginSql } = require(sqlPath)
const { genPassword } = require('../utils/secret')
/**
 * 注册实现步骤
 *  1. 检测表单数据是否合法
 *  2. 检测用户名是否被占用
 *  3. 对密码进行加密
 *  4. 插入到数据库中
 */
regUser = async (req, res) => {
    const { username, password } = req.body
    // 检测表单数据是否合法
    if (!checkUsername(username)) {
        let result = {
            code: 0,
            msg: '用户名不合法'
        }
        return res.send(result)
    } else {
        // 检测用户名是否被占用
        let isRegisterRes = await isRegisterSql(username)
        if (isRegisterRes.code === 0) {
            return res.send(isRegisterRes.message)
        } else {
            let result = checkPassword(password)
            if (result.code === 0) {
                // 密码合法加入数据库
                let addRegisterRes = await addRegisterSql({ username, password: genPassword(password), nickname: username, email: 'test' })
                return res.send(addRegisterRes)
            }
        }
    }
}

login = async (req, res) => {
    const { username, password } = req.body
    let checkLoginRes = await checkLoginSql(username, password)
    res.send(checkLoginRes)
}

module.exports = {
    regUser,
    login
}